package com.phcx.corporate.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;

/*
 * @Author: zmh
 * @Date: 2023/04/11/9:58
 * @Description:
 */
@Slf4j
public class HttpUtils {

    public static String get (String url) throws URISyntaxException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        log.info("[get-url]  ====> "+url);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        log.info("[get-result]  ====> "+result);
        return result;
    }

    public static <T> T get (String url,Class<T> clazz) throws URISyntaxException, IOException {
        String result = get(url);
        return JSON.parseObject(result, clazz);
    }

    public static String post (String url,String param) throws IOException {
        // 显示url，param日志
        log.info("[reqJson] =====>>> " + param);
        log.info("[url]     =====>>> " + url);
        // 发送post请求获取二维码信息
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);

        StringEntity entity = null;
        entity = new StringEntity(param,"UTF-8");
        post.setEntity(entity);
        post.setHeader("Content-type", "application/json");

        HttpResponse response = null;
        try {
            response = client.execute(post);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String responseBody = EntityUtils.toString(response.getEntity());
        log.info("[responseBody]  =====>>> "+responseBody);
        return responseBody;
    }

    public static String post (String url,Object object) throws IOException {
        String param = JSON.toJSONString(object);
        return post(url, param);
    }

    public static <T> T post (String url,Object object,Class<T> clazz) throws IOException {
        String param = JSON.toJSONString(object);
        String response = post(url, param);
        return JSON.parseObject(response, clazz);
    }
}
